<?php
$action = $_GET['action'];
switch($action) {
case 'init_data_list':
	init_data_list();
	break;
case 'add_row':
	add_row();
	break;
case 'del_row':
	del_row();
	break;
case 'edit_row':
	edit_row();
	break;
case 'sel_row':
	sel_row();
	break;
case 'select_row':
	select_row();
	break;
}

function select_row(){
	$datanum=$_POST['num'];
	$sql = "SELECT * FROM user WHERE `number` =".$datanum;
  $query = query_sql($sql);
	while($row = $query->fetch_assoc()){
		$data= $row;
	}
	echo json_encode($data);
}

function sel_row(){
	$dataid = $_POST['dataid'];	
	$sql = "SELECT * FROM `user` WHERE `id` = " . $dataid;
	$query = query_sql($sql);
	while($row = $query->fetch_assoc()){
		$data=$row['number']; 
	}
	echo json_encode($data);
}

function init_data_list(){
	$sql = "SELECT * FROM `user`";
	$query = query_sql($sql);
	while($row = $query->fetch_assoc()){
		$data[] = $row;
	}
	echo json_encode($data);
}

function del_row(){
	$dataid = $_POST['dataid'];	
	$sql = "DELETE FROM `user` WHERE `id` = " . $dataid;
	if(query_sql($sql)){
		echo "ok";	
	} else {
		echo "db error ...";	
	}
}

function add_row(){
	$sql = 'INSERT INTO `user` ( `username`,`password`,`name`,`number`) VALUES( ';
	for($i = 0 ; $i < 4 ; $i++){
			$sql .= '\'' . $_POST['col_' . $i] . '\', ';
	}	
	$sql = trim($sql,", ");
	$sql .= ")";
	if($res = query_sql($sql,"SELECT LAST_INSERT_ID() as LD")){
		$d = $res->fetch_assoc();
		echo $d['LD'];
	} else {
		echo "db error ...";	
	}
}

function edit_row(){
	$sql = 'UPDATE `user` SET ';
	$id = $_POST['id'];
	unset($_POST['id']);
	for($i = 0 ; $i < 4 ; $i++){
		$sql .= ' `c_' . chr(97+$i) . '` = \'' . $_POST['col_' . $i] . '\' , ';
	}
	$sql = trim($sql,", ");
	$sql .= ' WHERE `id` = ' . $id ;

	if(query_sql($sql)){
		echo "ok";	
	} else {
		echo "db error ...";	
	}
}

function query_sql(){
	$mysqli = new mysqli("127.0.0.1", "root", "123456", "test_db");
	$sqls = func_get_args();
	foreach($sqls as $s){
		$query = $mysqli->query($s);
	}
	$mysqli->close();
	return $query;
}

